<template>
  <div class="rent_add">
    <!-- 标题 -->
    <my-title title="发布房源"></my-title>

    <van-form >
      <!-- 房屋出租信息发布列表 -->
      <div class="rent_list">
        <!-- 头部 -->
        <div class="rent_list_header rent_add_header">
          房源信息
        </div>
        <!-- 整体 -->
        <van-cell-group class="rent_list_body">
          <!-- 小区名称 -->
          <van-field
            @click="$router.push('/rent/search')"
            class="bag"
            v-model="value"
            label="小区名称"
            placeholder="请输入小区名称"
            right-icon="arrow"
            input-align="right"
          />
          <!-- 租金 -->
          <van-field
            v-model.trim="form.price"
            label="租金"
            placeholder="请输入租金/月"
          >
            <template #extra>
              <span class="extra">￥/月</span>
            </template>
          </van-field>
          <!-- 建筑面积 -->
          <van-field
            v-model="form.size"
            label="建筑面积"
            placeholder="请输入建筑面积"
          >
            <template #extra>
              <span class="extra">㎡</span>
            </template>
          </van-field>
          <!-- 户型 -->
          <van-field
            class="bag"
            v-model="roomTypeValue"
            label="户型"
            placeholder="请选择"
            right-icon="arrow"
            input-align="right"
            @click="isShowRoomType = true"
          />
          <!-- 所在楼层 -->
          <van-field
            class="bag"
            v-model="floorValue"
            label="所在楼层"
            placeholder="请选择"
            right-icon="arrow"
            input-align="right"
            @click="isShowFloor = true"
          />
          <!-- 朝向 -->
          <van-field
            class="bag"
            v-model="orientedValue"
            label="朝向"
            placeholder="请选择"
            right-icon="arrow"
            input-align="right"
            @click="isShowOriented = true"
          />
        </van-cell-group>
      </div>

      <!-- 房屋标题 -->
      <div class="add_title">
        <!-- 头部 -->
        <div class="rent_add_header">
          房屋标题
        </div>
        <van-field v-model.trim="form.title" placeholder="请输入标题（例如：整租 小区名 2室 5000元）" />
      </div>

      <!-- 房屋图像 -->
      <div class="add_img">
        <!-- 头部 -->
        <div class="rent_add_header">
          房屋图像
        </div>
        <!-- 图片上传 -->
        <van-field name="fileList" >
          <template #input>
            <van-uploader v-model="fileList" :after-read="onFile" @delete="onFile" />
          </template>
        </van-field>
      </div>

      <!-- 房屋配置 -->
      <div class="add_img pad-b">
        <!-- 头部 -->
        <div class="rent_add_header" style="background-color: #fff;">
          房屋配置
        </div>
        <van-grid :column-num="5" :border="false">
          <van-grid-item
            :class="{'icon-color':supportingList.indexOf(item.label)!==-1}"
            @click="supportingChange(item.label)"
            v-for="(item,index) in supporting"
            :key="item.label"
            :icon="iconList[index]"
            :text="item.label"
          />
        </van-grid>
      </div>

      <!-- 房屋描述 -->
      <div class="add_img pad-b">
        <!-- 头部 -->
        <div class="rent_add_header" style="background-color: #fff;">
          房屋描述
        </div>
        <van-field
          v-model.trim="form.description"
          type="textarea"
          placeholder="请输入房屋描述信息"
          :autosize="{ minHeight: 123 }"
          maxlength="100"
        />
      </div>

      <!-- 取消提交按钮 -->
      <div class="change_btn">
        <van-button @click="onCancel" class="cancel-btn" type="primary" block>取消</van-button>
        <van-button @click="onSubmit" class="confirm-btn" type="primary" block>提交</van-button>
      </div>

    </van-form>
    <!-- 户型选择器弹出层 -->
    <van-popup v-model="isShowRoomType" position="bottom">
      <van-picker
        show-toolbar
        :columns="roomType.map(item => item.label).sort()"
        @confirm="roomTypeConfirm"
        @cancel="isShowRoomType = false"
      />
    </van-popup>

    <!-- 所在楼层选择器弹出层 -->
    <van-popup v-model="isShowFloor" position="bottom">
      <van-picker
        show-toolbar
        :columns="floor.map(item => item.label).sort()"
        @confirm="floorConfirm"
        @cancel="isShowFloor = false"
      />
    </van-popup>

    <!-- 朝向选择器弹出层 -->
    <van-popup v-model="isShowOriented" position="bottom">
      <van-picker
        show-toolbar
        :columns="oriented.map(item => item.label).sort()"
        @confirm="orientedConfirm"
        @cancel="isShowOriented = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'
import { getHouseConditions, PostHouseImg, PostHouse } from '@/api/houses.js'
import MyTitle from '@/components/MyTitle'
export default {
  name: 'RentAdd',
  data () {
    return {
      // 发布房源所需的数据
      form: {
        title: '',
        description: '',
        houseImg: '',
        oriented: '',
        supporting: '',
        price: '',
        roomType: '',
        size: '',
        floor: '',
        community: this.$route.query.id
      },
      // 控制选择器弹出层的出现
      isShowOriented: false,
      isShowRoomType: false,
      isShowFloor: false,
      // 存储请求返回的发布房源所需的条件数据
      floor: [],
      oriented: [],
      roomType: [],
      supporting: [],
      // 与表单绑定的值
      value: this.$route.query.name,
      roomTypeValue: '',
      floorValue: '',
      orientedValue: '',
      fileList: [],
      fileForm: new FormData(),
      // 图标
      iconList: ['smile-o', 'good-job-o', 'fire-o', 'sign', 'gift-card-o', 'tv-o', 'idcard', 'logistics', 'bar-chart-o', 'hotel-o'],
      // 房屋配置的存储
      supportingList: []
    }
  },
  components: {
    MyTitle
  },
  created () {
    this.loadHouseConditions()
  },

  methods: {
    // 点击提交按钮
    async onSubmit () {
      Toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true
      })
      try {
        const res = await PostHouseImg(this.fileForm)
        this.form.houseImg = res.data.body.join('|')
        const res2 = await PostHouse(this.form)
        console.log(res2)
        if (res2.data.status === 200) {
          Toast.clear()
          Dialog.confirm({
            title: '提示',
            message: '房源发布成功！',
            confirmButtonText: '继续发布',
            cancelButtonText: '去查看',
            confirmButtonColor: '#108ee9',
            width: 270
          })
            .then(() => {
              // on confirm,无变化
            })
            .catch(() => {
              // on cancel,去筛选页
              this.$router.push('/home/search')
            })
        } else {
          Toast.fail('未知错误！')
        }
      } catch (err) {
        if (err.response && err.response.status === 500) {
          Toast('未上传房屋图片！')
        } else {
          Toast.fail('发布失败！')
        }
      }
    },
    // 点击取消按钮
    onCancel () {
      Dialog.confirm({
        title: '提示',
        message: '放弃发布房源？',
        confirmButtonText: '继续编辑',
        cancelButtonText: '放弃',
        confirmButtonColor: '#108ee9',
        width: 270
      })
        .then(() => {
          // on confirm,无变化
        })
        .catch(() => {
          // on cancel,返回上一页面
          this.$router.push('/')
        })
    },
    // 添加房屋配置
    supportingChange (val) {
      const index = this.supportingList.indexOf(val)
      if (index === -1) {
        this.supportingList.push(val)
      } else {
        this.supportingList.splice(index, 1)
      }
      this.form.supporting = this.supportingList.join('|')
    },
    // 文件读取完成和删除后的回调函数
    onFile () {
      this.fileForm.delete('file')
      this.fileList.forEach(item => {
        this.fileForm.append('file', item.file)
      })
      // console.log(this.fileForm.getAll('file'))
    },
    // 获取发布房屋所需的条件
    async loadHouseConditions () {
      try {
        const res = await getHouseConditions()
        console.log(res)
        this.floor = res.data.body.floor
        this.oriented = res.data.body.oriented
        this.roomType = res.data.body.roomType
        this.supporting = res.data.body.supporting
      } catch (err) {
        Toast.fail('获取发布房屋所需的条件失败')
      }
    },
    // 户型Confirm
    roomTypeConfirm (val) {
      this.roomTypeValue = val
      this.isShowRoomType = false
      this.roomType.forEach(item => {
        if (item.label === val) {
          this.form.roomType = item.value
        }
      })
    },
    // 所在楼层Confirm
    floorConfirm (val) {
      this.floorValue = val
      this.isShowFloor = false
      this.floor.forEach(item => {
        if (item.label === val) {
          this.form.floor = item.value
        }
      })
    },
    // 朝向Confirm
    orientedConfirm (val) {
      this.orientedValue = val
      this.isShowOriented = false
      this.oriented.forEach(item => {
        if (item.label === val) {
          this.form.oriented = item.value
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.rent_add{
  font-family: "Microsoft YaHei";
  padding-bottom: 45px;
  // 点击改变icon颜色
  .icon-color{
    color: #21b97a;
    /deep/.van-grid-item__text{
    color: #21b97a;
    }
  }
  // 房屋出租信息发布列表样式
  .rent_list{
    // 头部
    .rent_list_header{
      color: #21b97a;
      background-color: #fff;
      font-size: 15px;
    }
  }
  // 公共头部样式
  .rent_add_header{
    padding: 15px 15px 9px;
    font-size: 14px;
    color: #333;
    width: 100%;
    box-sizing: border-box;
    border-bottom:1px solid #ebedf0;
  }
  // extra输入框额外内容样式
  .extra{
    color: #888;
    font-size: 14px;
  }
  // 点击改变背景色
  .bag{
    &:active{
      background-color: #ddd;
    }
  }
  // 下边距
  .pad-b{
    padding-bottom: 20px;
    background-color:#f6f5f6;
  }
  // 下方确认取消按钮样式
  .change_btn{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    height: 45px;
    .van-button{
      height: 45px;
      font-size: 15px;
      border: none;
    }

    // 取消按钮
    .cancel-btn{
      flex: 1;
      color: #21b97a;
      background-color: #fff;
    }
    // 提交按钮
    .confirm-btn{
      flex: 1;
      color: #fff;
      background-color: #21b97a;
    }
  }
}

</style>
